﻿/*global Qiniu */
/*global plupload */
/*global FileProgress */
var axupimgs = parent.axupimgs;
var file_list = []; //存放本地文件的数组
parent.axupimgs.res = [];
var file_i = 0;
$(function() {
	
	var filekey = "";
    var uploader = Qiniu.uploader({
        runtimes: 'html5,flash,html4',
        browse_button: 'pickfiles',
        container: 'container',
        drop_element: 'container',
        max_file_size: '5mb',
        flash_swf_url: 'components/plupload/Moxie.swf',
        dragdrop: true,
        chunk_size: '5mb',
        multi_selection: !(mOxie.Env.OS.toLowerCase()==="ios"),
		uptoken_func: function(file){
			var key = "",pre = "";
			var datestr = new Date().Format("yyyyMMdd");
			var randomkey = getRandom(5);
			var nowtime = new Date().getTime();
			var ext = getFileExtension(file.name);
			key = ext ? datestr+"/"+randomkey+nowtime + '.' + ext : datestr+"/"+randomkey+nowtime;
			if(isImage(key)){
				pre = "web/richpic/";
			}else{
				pre = "scripts/";
			}
			console.log('hello man,the file key is '+pre+key);
			key = pre+key;
			filekey = key;
		    var ajax = new XMLHttpRequest();
		    ajax.open('GET', $('#uptoken_url').val()+"?key="+key, false);
			ajax.setRequestHeader("If-Modified-Since", "0");
			ajax.send();
			if (ajax.status === 200) {
			    var res = JSON.parse(ajax.responseText);
			    console.log('custom uptoken_func:' + res.uptoken);
			    return res.uptoken;
			} else {
			    console.log('custom uptoken_func err');
			    return '';
		    }
		},
		get_new_uptoken: true,
        domain: $('#domain').val(),
		auto_start: true,
        log_level: 5,
        init: {
            'FilesAdded': function(up, files) {
                $('table').show();
                $('#success').hide();
                plupload.each(files, function(file) {
                    var progress = new FileProgress(file, 'fsUploadProgress');
                    progress.setStatus("等待...");
                    progress.bindUploadCancel(up);
                });
            },
            'BeforeUpload': function(up, file) {
                var progress = new FileProgress(file, 'fsUploadProgress');
                var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                if (up.runtime === 'html5' && chunk_size) {
                    progress.setChunkProgess(chunk_size);
                }
            },
            'UploadProgress': function(up, file) {
                var progress = new FileProgress(file, 'fsUploadProgress');
                var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                progress.setProgress(file.percent + "%", file.speed, chunk_size);
            },
            'UploadComplete': function() {
                $('#success').show();
            },
            'FileUploaded': function(up, file, info) {
                var progress = new FileProgress(file, 'fsUploadProgress');
                progress.setComplete(up, info);
                
                file_list.push({file:file,url:''});
                
                file_list[file_i].url = $("#domain").val()+filekey;
				parent.axupimgs.res = file_list;
				filename = filekey.split('/').pop();
                
                var vDom = document.createDocumentFragment();
                let li = document.createElement('li');
                li.setAttribute('class','up-no');
                li.setAttribute('data-time',new Date().getTime());
                li.innerHTML='<div class="picbox"><img src="'+$("#domain").val()+filekey+'"></div><div class="namebox"><span>'+filename+'</span></div><div class="tools"></div>';
                vDom.appendChild(li);
                document.querySelector('#file_list').appendChild(vDom);
               
                file_i++;
            },
            'Error': function(up, err, errTip) {
                $('table').show();
                var progress = new FileProgress(err.file, 'fsUploadProgress');
                progress.setError();
                progress.setStatus(errTip);
                $("#result").html("上传出错"+err);
                $("#result").show();
            },
			'Key': function(up, file) {
                if(isImage(filekey)){
    				pre = "web/richpic/";
    			}else{
    				pre = "scripts/";
    			}
				console.log('hello man,the file key is '+filekey);
				return filekey;
			}
        }
    });
    getFileExtension = function(filename) {
        var tempArr = filename.split(".");
        var ext;
        if (tempArr.length === 1 || (tempArr[0] === "" && tempArr.length === 2)) {
            ext = "";
        } else {
            ext = tempArr.pop().toLowerCase();
        }
        return ext;
    };
	isImage = function(url) {
        url = url.split(/[?#]/)[0];
        return (/\.(png|jpg|jpeg|gif|bmp)$/i).test(url);
    };
    uploader.bind('FileUploaded', function() {
        console.log('hello man,a file is uploaded');
    });
    $('#container').on(
        'dragenter',
        function(e) {
            e.preventDefault();
            $('#container').addClass('draging');
            e.stopPropagation();
        }
    ).on('drop', function(e) {
        e.preventDefault();
        $('#container').removeClass('draging');
        e.stopPropagation();
    }).on('dragleave', function(e) {
        e.preventDefault();
        $('#container').removeClass('draging');
        e.stopPropagation();
    }).on('dragover', function(e) {
        e.preventDefault();
        $('#container').addClass('draging');
        e.stopPropagation();
    });

    $('body').on('click', 'table button.btn', function() {
        $(this).parents('tr').next().toggle();
    });	
});
function getRandom(param){
	var size = "undefined" ? 5 : param;
	var r = "";
	for(var i=0;i<size;i++){
		r += Math.floor(Math.random()*10);
	}
	return r;
}
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}